import { updateUserName } from "@/api/team/tember/update"
import { Teamate } from "@/type/teamate"
import { Button, Input, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader } from "@nextui-org/react"
import { useEffect, useState } from "react"
import toast from "react-hot-toast"

const RenameModal = ({ isOpen, onOpenChange, detail, getTeamateData }: { getTeamateData: () => void, isOpen: boolean, onOpen?: () => void, onOpenChange: () => void, detail: Teamate | null }) => {

    const [value, setValue] = useState<string>("")
    useEffect(() => {
        if (detail != null)
            setValue(detail.name)
    }, [detail])

    return (
        <>
            <Modal
                backdrop="opaque"
                placement="center"
                size="sm"
                classNames={{
                    backdrop: "bg-gradient-to-t from-zinc-900 to-zinc-900/10 backdrop-opacity-20",
                }}
                isOpen={isOpen}
                onOpenChange={onOpenChange}
            >
                <ModalContent>
                    {(onClose) => (
                        <>
                            <ModalHeader className="flex flex-col gap-1">重命名</ModalHeader>
                            <ModalBody>
                                <Input onValueChange={(v) => {
                                    if (detail == null) return
                                    setValue(v)
                                }} value={value} label="NewName" type="text" variant={"underlined"} />
                            </ModalBody>
                            <ModalFooter>
                                <Button size="sm" color="danger" variant="light" onPress={onClose}>
                                    关闭
                                </Button>
                                <Button size="sm" color="primary" onPress={async () => {
                                    if (detail != null) {
                                        const result = await updateUserName({ ...detail, name: value } as Teamate)
                                        toast.dismiss()
                                        if (result.code == 200) {
                                            detail.name = value
                                            setValue("")
                                            toast.success(result.message)
                                            onClose()
                                            getTeamateData()
                                        } else {
                                            toast.error(result.message)
                                        }
                                    }
                                }}>
                                    提交
                                </Button>
                            </ModalFooter>
                        </>
                    )}
                </ModalContent>
            </Modal>
        </>
    )
}

export default RenameModal